{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv, find_dotenv\n",
    "\n",
    "# 读取本地/项目的环境变量。\n",
    "\n",
    "# find_dotenv() 寻找并定位 .env 文件的路径\n",
    "# load_dotenv() 读取该 .env 文件，并将其中的环境变量加载到当前的运行环境中  \n",
    "# 如果你设置的是全局的环境变量，这行代码则没有任何作用。\n",
    "_ = load_dotenv(find_dotenv())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[WARNING][2024-11-28 22:30:26.019] redis_rate_limiter.py:21 [t:25604]: No redis installed, RedisRateLimiter unavailable. Ignore this warning if you don't need to use qianfan SDK in distribution environment\n"
     ]
    }
   ],
   "source": [
    "import qianfan\n",
    "\n",
    "def gen_wenxin_messages(prompt):\n",
    "    '''\n",
    "    构造文心模型请求参数 messages\n",
    "\n",
    "    请求参数：\n",
    "        prompt: 对应的用户提示词\n",
    "    '''\n",
    "    messages = [{\"role\": \"user\", \"content\": prompt}]\n",
    "    return messages\n",
    "\n",
    "\n",
    "def get_completion(prompt, model=\"ERNIE-Tiny-8K\", temperature=0.01):\n",
    "    '''\n",
    "    获取文心模型调用结果\n",
    "\n",
    "    请求参数：\n",
    "        prompt: 对应的提示词\n",
    "        model: 调用的模型，默认为 ERNIE-Bot，也可以按需选择 ERNIE-Bot-4 等其他模型\n",
    "        temperature: 模型输出的温度系数，控制输出的随机程度，取值范围是 0~1.0，且不能设置为 0。温度系数越低，输出内容越一致。\n",
    "    '''\n",
    "\n",
    "    chat_comp = qianfan.ChatCompletion()\n",
    "    message = gen_wenxin_messages(prompt)\n",
    "\n",
    "    resp = chat_comp.do(messages=message, \n",
    "                        model=model,\n",
    "                        temperature = temperature,\n",
    "                        system=\"你是一名个人助理-小鲸鱼\")\n",
    "\n",
    "    return resp[\"result\"]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[ERROR][2024-11-28 22:31:35.822] base.py:134 [t:25604]: http request url https://qianfan.baidubce.com/wenxinworkshop/service/list failed with http status code 403\n",
      "error code from baidu: IamSignatureInvalid\n",
      "error message from baidu: IamSignatureInvalid, cause: Could not find credential.\n",
      "request headers: {'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Host': 'qianfan.baidubce.com', 'request-source': 'qianfan_py_sdk_v0.4.12.1', 'x-bce-date': '2024-11-28T14:31:35Z', 'Authorization': 'bce-auth-v1//2024-11-28T14:31:35Z/300/content-type;x-bce-date;host;request-source/5f8b616b4027ed9d3b0f79cc67704f21fc2839f0436e0b46dfb96de4583ff683', 'Content-Length': '2'}\n",
      "request body: '{}'\n",
      "response headers: {'Bfe-Trace-Id': '668503b9068a0bb9ba36843d2da36f55', 'Content-Length': '0', 'Date': 'Thu, 28 Nov 2024 14:31:35 GMT', 'X-Bce-Error-Code': 'IamSignatureInvalid', 'X-Bce-Error-Message': 'IamSignatureInvalid, cause: Could not find credential.', 'X-Bce-Exception-Point': 'Gateway', 'X-Bce-Gateway-Region': 'BJ', 'X-Bce-Request-Id': '8d3854dc-bb0e-4528-9a80-eb48f234ebb4', 'Content-Type': 'text/plain; charset=utf-8'}\n",
      "response body: b''\n",
      "[WARNING][2024-11-28 22:31:35.823] base.py:1083 [t:25604]: fetch_supported_models failed: http request url https://qianfan.baidubce.com/wenxinworkshop/service/list failed with http status code 403\n",
      "error code from baidu: IamSignatureInvalid\n",
      "error message from baidu: IamSignatureInvalid, cause: Could not find credential.\n",
      "request headers: {'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Host': 'qianfan.baidubce.com', 'request-source': 'qianfan_py_sdk_v0.4.12.1', 'x-bce-date': '2024-11-28T14:31:35Z', 'Authorization': 'bce-auth-v1//2024-11-28T14:31:35Z/300/content-type;x-bce-date;host;request-source/5f8b616b4027ed9d3b0f79cc67704f21fc2839f0436e0b46dfb96de4583ff683', 'Content-Length': '2'}\n",
      "request body: '{}'\n",
      "response headers: {'Bfe-Trace-Id': '668503b9068a0bb9ba36843d2da36f55', 'Content-Length': '0', 'Date': 'Thu, 28 Nov 2024 14:31:35 GMT', 'X-Bce-Error-Code': 'IamSignatureInvalid', 'X-Bce-Error-Message': 'IamSignatureInvalid, cause: Could not find credential.', 'X-Bce-Exception-Point': 'Gateway', 'X-Bce-Gateway-Region': 'BJ', 'X-Bce-Request-Id': '8d3854dc-bb0e-4528-9a80-eb48f234ebb4', 'Content-Type': 'text/plain; charset=utf-8'}\n",
      "response body: b''\n",
      "[WARNING][2024-11-28 22:31:35.823] base.py:973 [t:25604]: This key `system` does not seem to be a parameter that the model `Yi-34B-Chat` will accept\n",
      "[INFO][2024-11-28 22:31:35.825] oauth.py:277 [t:25604]: trying to refresh token for ak `enA9Ab***`\n",
      "[INFO][2024-11-28 22:31:36.286] oauth.py:304 [t:25604]: successfully refresh token\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'你好！我叫 Yi，我是零一万物开发的一个智能助手，由零一万物的研究团队通过大量的文本数据进行训练，学习了语言的各种模式和关联，从而能够生成文本、回答问题、翻译语言的。我可以帮助你解答问题、提供信息，或者进行其他与语言处理相关的任务。如果你有任何问题或需要帮助的地方，请随时告诉我！'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_completion(\"你好，介绍一下你自己\", model=\"Yi-34B-Chat\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[ERROR][2024-11-28 22:32:25.457] base.py:134 [t:25604]: http request url https://qianfan.baidubce.com/wenxinworkshop/service/list failed with http status code 403\n",
      "error code from baidu: IamSignatureInvalid\n",
      "error message from baidu: IamSignatureInvalid, cause: Could not find credential.\n",
      "request headers: {'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Host': 'qianfan.baidubce.com', 'request-source': 'qianfan_py_sdk_v0.4.12.1', 'x-bce-date': '2024-11-28T14:32:25Z', 'Authorization': 'bce-auth-v1//2024-11-28T14:32:25Z/300/content-type;x-bce-date;host;request-source/0a64f898287b9608ab3572d88cd4e388d750485d9bb00c66e2bba5fe8d8a8f39', 'Content-Length': '2'}\n",
      "request body: '{}'\n",
      "response headers: {'Bfe-Trace-Id': '2a19b33578da9aa6e2bab5bc937c18c9', 'Content-Length': '0', 'Date': 'Thu, 28 Nov 2024 14:32:25 GMT', 'X-Bce-Error-Code': 'IamSignatureInvalid', 'X-Bce-Error-Message': 'IamSignatureInvalid, cause: Could not find credential.', 'X-Bce-Exception-Point': 'Gateway', 'X-Bce-Gateway-Region': 'BJ', 'X-Bce-Request-Id': '7e312729-8324-4db8-b1a4-3de7f2c6980b', 'Content-Type': 'text/plain; charset=utf-8'}\n",
      "response body: b''\n",
      "[WARNING][2024-11-28 22:32:25.458] base.py:1083 [t:25604]: fetch_supported_models failed: http request url https://qianfan.baidubce.com/wenxinworkshop/service/list failed with http status code 403\n",
      "error code from baidu: IamSignatureInvalid\n",
      "error message from baidu: IamSignatureInvalid, cause: Could not find credential.\n",
      "request headers: {'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Host': 'qianfan.baidubce.com', 'request-source': 'qianfan_py_sdk_v0.4.12.1', 'x-bce-date': '2024-11-28T14:32:25Z', 'Authorization': 'bce-auth-v1//2024-11-28T14:32:25Z/300/content-type;x-bce-date;host;request-source/0a64f898287b9608ab3572d88cd4e388d750485d9bb00c66e2bba5fe8d8a8f39', 'Content-Length': '2'}\n",
      "request body: '{}'\n",
      "response headers: {'Bfe-Trace-Id': '2a19b33578da9aa6e2bab5bc937c18c9', 'Content-Length': '0', 'Date': 'Thu, 28 Nov 2024 14:32:25 GMT', 'X-Bce-Error-Code': 'IamSignatureInvalid', 'X-Bce-Error-Message': 'IamSignatureInvalid, cause: Could not find credential.', 'X-Bce-Exception-Point': 'Gateway', 'X-Bce-Gateway-Region': 'BJ', 'X-Bce-Request-Id': '7e312729-8324-4db8-b1a4-3de7f2c6980b', 'Content-Type': 'text/plain; charset=utf-8'}\n",
      "response body: b''\n",
      "[INFO][2024-11-28 22:32:25.459] oauth.py:277 [t:25604]: trying to refresh token for ak `enA9Ab***`\n",
      "[INFO][2024-11-28 22:32:25.721] oauth.py:304 [t:25604]: successfully refresh token\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'你好，我是小鲸鱼，很高兴认识你。我是一名个人助理，致力于帮助你处理日常事务，提供所需的服务。'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_completion(\"你好，介绍一下你自己\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "· messages，即调用的 prompt。文心的 messages 配置与 ChatGPT 有一定区别，其不支持 max_token 参数，由模型自行控制最大 token 数，messages 中的 content 总长度、functions 和 system 字段总内容不能超过 20480 个字符，且不能超过 5120 tokens，否则模型就会自行对前文依次遗忘。文心的 messages 有以下几点要求：① 一个成员为单轮对话，多个成员为多轮对话；② 最后一个 message 为当前对话，前面的 message 为历史对话；③ 成员数目必须为奇数，message 中的 role 必须依次是 user、assistant。注：这里介绍的是 ERNIE-Bot 模型的字符数和 tokens 限制，而参数限制因模型而异，请在文心千帆官网查看对应模型的参数说明。\n",
    "\n",
    "· stream，是否使用流式传输。\n",
    "\n",
    "· temperature，温度系数，默认 0.8，文心的 temperature 参数要求范围为 (0, 1.0]，不能设置为 0。\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "jupyter38",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
